package com.sxhalo.fsms.controller.api;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.sxhalo.fsms.log.SysControllerLog;
import com.sxhalo.fsms.service.ISysRoleModulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import com.sxhalo.fsms.controller.BaseController;
import com.sxhalo.fsms.domain.SysModule;
import com.sxhalo.fsms.service.ISysModuleService;
import com.sxhalo.fsms.util.ApiResult;
import com.sxhalo.fsms.util.CookieUtils;
import com.sxhalo.fsms.util.MenuData;
import com.sxhalo.fsms.util.PageData;
import com.sxhalo.fsms.util.TokenUtil;
import com.sxhalo.fsms.util.TreeData;

@Controller
@RequestMapping("/api")
public class SysModuleController extends BaseController {

	@Autowired
	private ISysModuleService moduleService;
	@Autowired
	private ISysRoleModulesService rolemoduleService;


	@ResponseBody
	@RequestMapping(value = "/module", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findModule(Integer current, Integer pageSize, HttpServletRequest req) {
		String where = "1=1";
		String order = "sequence";
		if(!isBlank(req.getParameter("parentId"))) {
			where += " and parent_id = " + req.getParameter("parentId").trim() + "";
		}
		if(!isBlank(req.getParameter("moduleName"))) {
			where += " and module_name like '%" + req.getParameter("moduleName").trim() + "%'";
		}
		if (!isBlank(req.getParameter("moduleCode"))) {
			where += " and module_code like '%" + req.getParameter("moduleCode").trim() + "%'";
		}
		if (!isBlank(req.getParameter("relativePath"))) {
			where += " and relative_path like '%" + req.getParameter("relativePath").trim() + "%'";
		}
		return findList(current, pageSize, where, order, req);
	}
	
	public ApiResult findList(Integer current, Integer pageSize, String where, String order, HttpServletRequest req) {
		if (current == null && pageSize == null) {
			List<SysModule> list = moduleService.findWhereList(where, order);
			for (SysModule sysModule : list) {
				List<SysModule> children = moduleService.findWhereList("parent_id=" + sysModule.getModuleId(), order);
				sysModule.setChildren(children.size() > 0 ? children : null);
			}
			return ApiResult.retOK(req, list);
		} else {
			Integer start = pageSize * (current - 1);
			Integer count = moduleService.getCount(where);
			List<SysModule> list = moduleService.findPagerList(start, pageSize, where, order);
			for (SysModule sysModule : list) {
				List<SysModule> children = moduleService.findWhereList("parent_id=" + sysModule.getModuleId(), order);
				sysModule.setChildren(children.size() > 0 ? children : null);
			}
			PageData page = new PageData(current, pageSize, count, list);
			return ApiResult.retOK(req, page);
		}
	}
	
	@ResponseBody
	@SysControllerLog(operationName = "新增模块", modelName = "模块管理")
	@RequestMapping(value = "/module", method = RequestMethod.POST, produces="application/json;charset=UTF-8")
	public ApiResult saveModule(@RequestBody  SysModule record, String method, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		Integer maxId = moduleService.getMaxId();
		record.setModuleId(maxId + 1);
		record.setCreateTime(nowtime);
		moduleService.insertSelective(record);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "更新模块", modelName = "模块管理")
	@RequestMapping(value = "/module", method = RequestMethod.PUT, produces="application/json;charset=UTF-8")
	public ApiResult updateModule(@RequestBody  SysModule record, String method, HttpServletRequest req) {
		Timestamp nowtime = new Timestamp(System.currentTimeMillis());
		record.setUpdateTime(nowtime);
		moduleService.updateByPrimaryKeySelective(record);
		return ApiResult.retOK(req);
	}


	@SysControllerLog(operationName = "删除", modelName = "模块管理")
	@RequestMapping(value = "/module", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult delModule(Integer moduleId, HttpServletRequest req) {
		moduleService.deleteByPrimaryKey(moduleId);
		rolemoduleService.deleteByWhere(" module_id ="+moduleId);
		return ApiResult.retOK(req);
	}


	@ResponseBody
	@SysControllerLog(operationName = "批量删除", modelName = "字典管理")
	@RequestMapping(value = "/module/batchdel", method = RequestMethod.DELETE, produces="application/json;charset=UTF-8")
	public ApiResult batchDelModule(String ids, HttpServletRequest req) {

		moduleService.deleteByWhere(" id in ("+ids+")");
		rolemoduleService.deleteByWhere(" module_id in ("+ids+")");
		return ApiResult.retOK(req);
	}

	@ResponseBody
	@RequestMapping(value = "/module/menu", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findMenu(Integer roleId, HttpServletRequest req){
		String token = CookieUtils.getCookieValue(req, "token");
		if (token != null) {
			roleId = TokenUtil.getRoleId(token);
			List<MenuData> menuData = findMenuData(0, roleId);
			return ApiResult.retOK(req, menuData);
		}
		return ApiResult.retOK(req);
	}
	

	@ResponseBody
	@RequestMapping(value = "/module/tree", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	public ApiResult findTree(String type, HttpServletRequest req){
		List<TreeData> treeData = new ArrayList<>();
		if (type != null && "root".equals(type)) {
			TreeData item = new TreeData();
			item.setTitle("根目录");
			item.setValue("0");
			item.setKey("0");
			item.setChildren(findTreeData(0));
			treeData.add(item);
		} else {
			treeData = findTreeData(0);
		}
		return ApiResult.retOK(req, treeData);
	}
	
	private List<MenuData> findMenuData(Integer moduleId, Integer roleId) {
		List<MenuData> menuData = new ArrayList<MenuData>();
		String where = "module_id in (select module_id from sys_role_modules where role_id=" + roleId + ") and ";
		List<SysModule> list = moduleService.findWhereList(where + "disable=0 and parent_id=" + moduleId, "sequence");
		for (SysModule module : list) {
			MenuData item = new MenuData();
			item.setName(module.getModuleName());
			item.setPath(module.getRelativePath());
			item.setIcon(module.getIconName());
			if (module.getVisible() != null) {
				item.setHideInMenu(module.getVisible() == 0);
			}
			List<MenuData> children = findMenuData(module.getModuleId(), roleId);
			if(children.size() > 0) {
				item.setChildren(children);
			}
			menuData.add(item);
		}
		return menuData;
	}
	
	private List<TreeData> findTreeData(Integer moduleId) {
		List<TreeData> treeData = new ArrayList<TreeData>();
		List<SysModule> list = moduleService.findWhereList("disable=0 and parent_id=" + moduleId, "sequence");
		for (SysModule module : list) {
			TreeData item = new TreeData();
			item.setTitle(module.getModuleName());
			item.setKey(module.getModuleId().toString());
			item.setValue(module.getModuleId().toString());
			List<TreeData> children = findTreeData(module.getModuleId());
			if(children.size() > 0) {
				item.setChildren(children);
			}
			treeData.add(item);
		}
		return treeData;
	}
}
